﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Noria.Web.Utility
{
    public static class RazorUtility
    {
        public static string ApplyTemplate(string page, string query)
        {
            using (var sw = new StringWriter())
            {
                HttpWorkerRequest wr = new RazorRequest(page, query, sw);
                HttpRuntime.ProcessRequest(wr);
                return sw.ToString();
            }
        }

        public static void ApplyTemplateAndSave(string page, string query, string path, bool minimize)
        {
            var buffer = ApplyTemplate(page, query);

            if (minimize)
                buffer = buffer.HtmlMinimize();

            var fi = new FileInfo(path);
            if (!fi.Directory.Exists)
                fi.Directory.Create();

            File.WriteAllBytes(path, Encoding.UTF8.GetBytes(buffer));
        }

        public static string HtmlMinimize(this string source)
        {
            StringBuilder buffer = new StringBuilder(source);
            buffer.Replace("\r\n", " ").
                Replace("\t", " ").
                Replace("  ", " ").
                Replace("  ", " ").
                Replace("  ", " ").
                Replace("  ", " ").
                Replace("  ", " ").
                Replace("  ", " ").
                Replace("  ", " ").
                Replace("> <", "><");
            return buffer.ToString();
        }
    }
}
